//
//  ZFMapboxViewController.swift
//  map
//
//  Created by fyzq on 2024/1/24.
//

import UIKit
@_spi(Experimental) import MapboxMaps
import FloatingPanel
import RxSwift
import RxGesture
import GLKit
class ZFMapboxViewController: ZFBaseViewController {

    var mapManager :ZFMapManager!
    private var cancellables = Set<AnyCancelable>()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true

        let options = MapInitOptions(cameraOptions: CameraOptions(center: ZFMapManager.defaultLocation,zoom: 14), styleURI: StyleURI(url: URL(string: "mapbox://styles/su1qun/clrzslny1006y01paeq4rcr77")!))
        let mapView = MapView(frame: CGRect.zero, mapInitOptions: options);
        mapManager = ZFMapManager(mapView: mapView);
        mapManager.defalut()
        mapManager.setPuck2D()
        
        
        
        view.addSubview(mapView)
        mapView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

            
        
//        mapView.gestures.onLayerTap(<#T##layerId: String##String#>, handler: <#T##MapLayerGestureHandler##MapLayerGestureHandler##(QueriedFeature, MapContentGestureContext) -> Bool#>)
//        mapView.location.options.puckBearingEnabled = true
        
//        let offlineManager = OfflineManager()
//        let tileSetDescriptorOptions = TilesetDescriptorOptions(
//            styleURI: .outdoors,
//            zoomRange: 0...16,
//            tilesets: ["mapbox://mapbox.mapbox-streets-v8"])
//
//        let tilesetDescriptor = offlineManager.createTilesetDescriptor(for: tileSetDescriptorOptions)
//
//        offlineManager.removeStylePack(for: .streets) { result in
//            // handle style pack removal result
//        }

//        ZFNetRequest.request(token: ZFRequestApi.groupList).subscribe(onNext:{res in
//            print("---\(res)")
//            if res.status == 200 {
//                
//            }
//        }).disposed(by: dis)
        addGestrue()
        setFloat()
 


    }
    
}


/**
 操作地图手势
 */
extension ZFMapboxViewController {
    
    fileprivate func addGestrue(){
        
        mapManager.onCameraChanged().subscribe {[weak self] camera in
            guard let self = self else {return}
            let pitch = camera.cameraState.pitch
            let bo = pitch > 45 ? true : false
            if bo != self.locationControlView.pitchView.isPitch {
                self.locationControlView.pitchView.isPitch = bo
            }
        }.disposed(by: dis)
        
        mapManager.onMapLongPress().subscribe {[weak self] data in
            
            guard let self = self,
                let elevation = self.mapManager.mapView?.mapboxMap.elevation(at: data.coordinate),
                let exaggeration = self.mapManager.mapView?.mapboxMap.terrainProperty("exaggeration") else {
                return
            }
            UIView.feedback()
            self.fpc.move(to: .tip, animated: true)
            let signView = ZFSignAlertView()
            signView.location = data.coordinate;
            signView.elevation = elevation / (exaggeration.value as! Double)
            ZFSwiftMessage.show(view: signView,presentationStyle: .bottom)
            
            signView.signBottomView.subject.subscribe(onNext: {[weak self]idx in
                guard let self = self else {return}
                self.onSignAction(index: idx)
            }).disposed(by: self.dis)
            
        }.disposed(by: dis)
        
        mapManager.onMapLoaded().subscribe {[weak self] data in
            guard let self = self else {return}
            self.mapManager.setTerrain()
            self.mapManager.setElevation()
            self.mapManager.setRegionLayer()
            self.onMapConfig()
        }.disposed(by: dis)


        

    }
    
}

/**
 主要是地图配置
 */
extension ZFMapboxViewController{
    func onMapConfig(){
        ///配置信息
        guard let config = ZFMapConfigModal.getMapConfig(),
        let mapView = self.mapManager.mapView,
        let point = config.point,
        let compass = config.compass else {
            return
        }
        ///是否可以显示3d
        mapView.gestures.pitchGestureRecognizer.isEnabled = config.enablePitch;
        mapView.gestures.rotateGestureRecognizer.isEnabled = config.enableRotate
        self.mapManager.updateElevationVisibility(value: config.enableElevation)
        self.szImageView.isHidden = !point.showImage;
        
        do{
            try mapView.mapboxMap.allLayerIdentifiers.filter {$0.id.contains("road-") && $0.type == .line }.forEach {
                try mapView.mapboxMap.updateLayer(withId: $0.id, type: LineLayer.self) { layer in
                    layer.visibility = .constant(config.enableRoad ?.visible : .none)
               }
            }
            try mapView.mapboxMap.allLayerIdentifiers.filter {$0.id.contains("-label") && $0.type == .symbol }.forEach {
                try mapView.mapboxMap.updateLayer(withId: $0.id, type: SymbolLayer.self) { layer in
                    layer.visibility = .constant(config.enablePlace ? .visible : .none)
               }
            }
        }catch{
            print("路线显示失败")
        }
    
    }
    
}

/**
 长按操作
 1. 导航 2 街景 3.分享 4 添加兴趣点
 */
extension ZFMapboxViewController {
    
    fileprivate func onSignAction(index:Int){
        ZFSwiftMessage.hide()
        switch index {
        case 0 :
            break;
        case 1:
            break
        case 2:
            break
        case 3:
            let vc = ZFInterestViewController()
            self.navigationController?.pushViewController(vc, animated: true)
            break
            
        default: break
            
        }
        
    }
}
